import { Message } from "element-ui"

export default ({ $axios, app }) => {
  $axios.onRequest(
    (config) => {
      const b = {
        platform: "official-web",
        deviceModel: "browser",
        osVersion: "c2c-1.0",
        appVersion: "1.0.0",
        appName: "client-c2c",
        timestamp: new Date().getTime()
      }
      config.isPrompt = config.isPrompt == null ? true : config.isPrompt
      // 调用接口时设置对应的Accept-Language为zh-CN或者en-US，服务端根据传过去的值进行判断，做中英文切换
      config.headers["Accept-Language"] = app.$cookies.get("lang") || "en-US"
      config.url = `${config.url}?platform=${b.platform}&deviceModel=${b.deviceModel}&osVersion=${b.osVersion}&appVersion=${b.appVersion}&appName=${b.appName}&timestamp=${b.timestamp}`
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  //响应拦截（配置返回的数据）
  $axios.onResponse(
    (res) => {
      //根据返回的code值来做不同的处理(和后端约定)
      switch (res.data.code) {
        case 0:
          return res.data
          break
        default:
          Message({
            message: res.data.msg || "网络延迟，请稍后再试",
            type: "warning"
          })
          return Promise.reject(res)
          break
      }
    },
    (error) => {
      let data = error.response.status
      if (data == 401) {
        // router.push(`/login?origin=${router.app.$route.fullPath}`);
      } else {
        Message({
          message: "网络延迟，请稍后再试",
          type: "warning"
        })
      }
      return Promise.reject(error)
    }
  )
}
